package cn.highedu.http;

import cn.highedu.mvc.HandlerMapping;
import cn.highedu.mvc.UserController;
import cn.highedu.mvc.ViewResolver;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.HashMap;

/**
 * 封装请求处理功能
 */
public class DispatcherServlet {
    private static File root;
    private static File staticDir;
    static {
        //初始化静态资源路径， 用于加载静态资源
        try {
            root = new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(root, "static");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private static DispatcherServlet instance = new DispatcherServlet();

    private DispatcherServlet(){
    }
    public static DispatcherServlet getInstance() {
        return instance;
    }

    /**
     * 处理请求过程，根据请求的URI，找到对应文件
     * @param request 解析好请求信息
     * @param response 向客户端发送的信息
     */
    public void service(HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
        //String uri = request.getUri();
        String path = request.getRequestURI();
        ViewResolver viewResolver = ViewResolver.getInstance();
        HandlerMapping handlerMapping = HandlerMapping.getInstance();
        try {
            //根据请求路径找到，对应的控制器方法
            Method method = handlerMapping.getHandlerMethod(path);
            if (method != null) {
                //利用反射创建控制器对象
                Class cls = method.getDeclaringClass();
                Object obj = cls.newInstance();
                //使用反射执行方法
                HashMap<String, Object> model = new HashMap<>();
                String view = (String) method.invoke(obj, request, response, model);
                String html = viewResolver.render(view, model);
                response.setContent(html);
            }else {
                File file = new File(staticDir, path);
                //检查一下 file，如果是文件夹，就现在文件夹中的index.html
                if (file.isDirectory()){
                    file = new File(file, "index.html");
                }
                if (file.isFile()) {
                    response.setContentFile(file);
                } else {
                    File errorPage = new File(staticDir, "404.html");
                    response.setStatusCode(404);
                    response.setStatusReason("Not Found");
                    response.setContentFile(errorPage);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            //发生意外时候，反馈500页面
            response.setStatusCode(500);
            response.setStatusReason("Internal Server Error");
            File file500 = new File(staticDir, "500.html");
            response.setContentFile(file500);
        }

    }
}
